<?

class session
{
	static private $instance;

	public static function instance()
	{
		return self::$instance ? self::$instance : self::$instance = new self;
	}

	private function  __construct()
	{
		if ( PHP_SAPI == 'cli' ) return;
		if ( $_POST['PHPSESSID'] ) self::set_id ($_POST['PHPSESSID']);
		session_start();
	}

	public static function destroy()
	{
		session_destroy();
	}

	public static function clear()
	{
		session_unset();
	}

	public static function set_id( $id )
	{
		session_id($id);
	}

	public static function get( $name )
	{
		return self::instance()->$name;
	}

	public static function set( $name, $value )
	{
		return self::instance()->$name = $value;
	}

	public static function delete( $name )
	{
		self::set($name, null);
	}

	public function __get( $name )
	{
		return $_SESSION[$name];
	}

	public function __set($name, $value)
	{
		return $_SESSION[$name] = $value;
	}

	public static function has_credentials( $credentials )
	{
		if ( !is_array($credentials) ) $credentials = array( $credentials );
		$session_credentials = self::get('credentials') ? self::get('credentials') : array();

		return array_intersect($credentials, $session_credentials) == $credentials;
	}

	public static function set_credentials( $credentials )
	{
		$current_credentials = self::get('credentials');
		if ( !is_array($credentials) ) $credentials = array($credentials);

		foreach ( $credentials as $credential ) $current_credentials[] = $credential;
		$current_credentials = array_unique($current_credentials);

		self::set('credentials', $current_credentials);
	}

	public static function authorize( $user_id, $credentials = array('user') )
	{
		self::user_id($user_id);
		self::set_credentials($credentials);
	}

	public static function un_authorize()
	{
		self::set('user_id', null);
		self::set('credentials', array());
		session_destroy();
	}

	public static function user_id( $user_id = null )
	{
		return $user_id ? self::set('user_id', $user_id) : self::get('user_id');
	}
}